<template>
	<div class="edit-popup">
		<popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit"
			@close="handleClose">
			<el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
				<el-form-item label="上级品牌" prop="pid" v-if="formData.pid !== 0">
					<el-tree-select class="flex-1" v-model="formData.pid" :data="optionsData.dept" clearable
						node-key="id" :props="{
                            value: 'id',
                            label: 'name'
                        }" check-strictly :default-expand-all="true" placeholder="请选择上级品牌" />
				</el-form-item>
				<el-form-item label="品牌名称" prop="name">
					<el-input v-model="formData.name" placeholder="请输入品牌名称" :maxlength="100" />
				</el-form-item>
				<el-form-item label="" prop="logo">
					<material-picker v-model="formData.logo" />
				</el-form-item>
				<el-form-item label="首字母（大写）" prop="mobile">
					<el-input v-model="formData.first" placeholder="请输入首字母（大写）" />
				</el-form-item>
			</el-form>
		</popup>
	</div>
</template>
<script lang="ts" setup>
	import type { FormInstance } from 'element-plus'

	import { apiCarBrandLists, apiCarBrandAdd, apiCarBrandEdit, apiCarBrandDetail, apiCarBrandAll } from '@/api/car_brand'

	import Popup from '@/components/popup/index.vue'
	import { useDictOptions } from '@/hooks/useDictOptions'

	const emit = defineEmits(['success', 'close'])
	const formRef = shallowRef<FormInstance>()
	const popupRef = shallowRef<InstanceType<typeof Popup>>()
	const mode = ref('add')
	const popupTitle = computed(() => {
		return mode.value == 'edit' ? '编辑品牌' : '新增品牌'
	})
	const formData = reactive({
		id: '',
		pid: '' as string | number,
		name: '',
		leader: '',
		mobile: '',
		sort: 0,
		first:'',
		logo:''
	})

	const formRules = {
		pid: [
			{
				required: true,
				message: '请选择上级品牌',
				trigger: ['change']
			}
		],
		name: [
			{
				required: true,
				message: '请输入品牌名称',
				trigger: ['blur']
			}
		]
	}

	const { optionsData } = useDictOptions<{
		dept : any[]
	}>({
		dept: {
			api: apiCarBrandAll
		}
	})

	const handleSubmit = async () => {
		await formRef.value?.validate()
		mode.value == 'edit' ? await apiCarBrandEdit(formData) : await apiCarBrandAdd(formData)
		popupRef.value?.close()
		emit('success')
	}

	const open = (type = 'add') => {
		mode.value = type
		popupRef.value?.open()
	}

	const setFormData = (data : Record<any, any>) => {
		for (const key in formData) {
			if (data[key] != null && data[key] != undefined) {
				//@ts-ignore
				formData[key] = data[key]
			}
		}
	}

	const getDetail = async (row : Record<string, any>) => {
		const data = await apiCarBrandDetail({
			id: row.id
		})
		setFormData(data)
	}

	const handleClose = () => {
		emit('close')
	}

	defineExpose({
		open,
		setFormData,
		getDetail
	})
</script>